//
//  SESettingViewController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/15.
//

import UIKit
import Photos

class SESettingViewController: SEBaseViewController {

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.tableFooterView = tableFooterView
            tableView.rowHeight = 50
            tableView.separatorColor = UIColor.init(hex: "EBECF0")
            tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            tableView.register(UINib(nibName: SESettingListCell.className, bundle: nil), forCellReuseIdentifier: SESettingListCell.reuseId)
            tableView.keyboardDismissMode = .onDrag
        }
    }

    @IBOutlet weak var appVersionLabel: UILabel! {
        didSet {
            appVersionLabel.text = "V\(UIDevice.appVersion)"
        }
    }

    var viewModel = SESettingViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "设置"
        // Do any additional setup after loading the view.
    }

    override func setupUI() {
        super.setupUI()

        viewModel.updateData = { status in
            switch status {
            case .success:
                SEHUD.show(message: "上传成功")
                self.tableView.reloadData()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.uploadUserAvator)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.uploadHandler = { status in
            switch status {
            case .success:
                self.uploadUserAvator()
            case .auth(let msg):
                self.presentLoginViewController(selector: nil) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.userNickHandler = { status in
            switch status {
            case .success:
                SEHUD.show(message: "修改成功")
            case .auth(let msg):
                self.presentLoginViewController(selector: nil) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.logoutHandler = { status in
            switch status {
            case .success:
                self.logoutSucess()
            case .auth(let msg), .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

    }

    private lazy var tableFooterView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: 30 + 48 + 30))
        guard !UserDefaults.authToken.isEmpty else { return view }
        let btnView = SERegistrationConfirmBtnView(frame: CGRect(x: 0, y: 0, width: 150, height: 48))
        btnView.center = view.center
        btnView.delegate = self
        btnView.title = "退出登录"
        view.addSubview(btnView)
        return view
    }()

    private func openPhotoSheet() {
        SEAlert.showImagePickerSheet(in: self) { _ in
            self.checkCameraPermission()
        } photoHandler: { _ in
            self.openPhotoLibrary()
        }
    }

    private func pushToChangePsd() {
        let vc = SEChangePsdViewController()
        navigationController?.pushViewController(vc, animated: true)
    }

    private func pushToAppStore() {
        UIApplication.shared.open(URL(string: "https://apps.apple.com/cn/app/id1569547793")!, options: [:], completionHandler: nil)
    }

}

// MARK: - UITableViewDataSource, UITableViewDelegate

extension SESettingViewController: UITableViewDataSource, UITableViewDelegate {

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SESettingListCell.reuseId, for: indexPath) as! SESettingListCell
        cell.delegate = self
        cell.updateCell(indexPath: indexPath)
        return cell
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let cell = tableView.cellForRow(at: indexPath) as? SESettingListCell else {
            return
        }
        switch cell.type {
        case .userId:
            print("userId")
        case .avator:
            openPhotoSheet()
        case .identity:
            print("identity")
        case .password:
           pushToChangePsd()
        case .update:
            pushToAppStore()
        }
    }

}

// MARK: - SERegistrationConfirmBtnViewDelegate

extension SESettingViewController: SERegistrationConfirmBtnViewDelegate {
    func registrationConfirmBtnViewAction(view: SERegistrationConfirmBtnView) {
        logout()
    }

    func logoutSucess() {
        UserTools.removeAllUserInfo()
        navigationController?.popToRootViewController(animated: true)
    }
}

// MARK: - UIImagePickerControllerDelegate

extension SESettingViewController {
    private func checkCameraPermission() {
        let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
        switch authStatus {
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { (granted) in
                if !granted {
                    dispatch_async_safely_main_queue {
                        SEAlert.show(in: self.navigationController,
                                     title: "无法访问您的相机",
                                     message: "请到设置 -> 隐私 -> 相机 ，打开访问权限",
                                     confirmTitle: "去设置") { _ in
                            SEOpenSettingURL()
                        }
                    }
                }
            }
        case .restricted, .denied:
            SEAlert.show(in: self.navigationController,
                         title: "无法访问您的相机",
                         message: "请到设置 -> 隐私 -> 相机 ，打开访问权限",
                         confirmTitle: "去设置") { _ in
                SEOpenSettingURL()
            }
        case .authorized:
            openCamera()
        default:
            break
        }
    }

    private func openCamera() {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        present(imagePicker, animated: true, completion: nil)
    }

    private func openPhotoLibrary() {
        UIScrollView.appearance().contentInsetAdjustmentBehavior = .automatic
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary
        imagePicker.modalPresentationStyle = .custom
        present(imagePicker, animated: true, completion: nil)
    }
}

extension SESettingViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            viewModel.uploadImg(image: image)
        }
        dismiss(animated: true) {
            UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
        }
    }
}

// APIRequest

extension SESettingViewController {
    @objc private func uploadUserAvator() {
        viewModel.uploadUserAvator()
    }

    @objc private func submitUserNick() {
        viewModel.submitUserNick()
    }

    private func logout() {
        viewModel.logout()
    }
}

// MARK: - SESettingListCellDelegate

extension SESettingViewController: SESettingListCellDelegate {
    func settingListCellEndEditing(listCell: SESettingListCell) {
        view.endEditing(true)
        guard let nick = listCell.textField.text else { return }
        if nick.isEmpty {
            tableView.reloadData()
        } else if nick == UserDefaults.userNick {
            return
        } else {
            viewModel.userNick = nick
            viewModel.submitUserNick()
        }
    }
}
